package cn.lovemmd.model.admin.controller;

import com.alibaba.fastjson2.JSON;
import cn.lovemmd.model.admin.common.Result;
import cn.lovemmd.model.admin.service.DownloadLogService;
import cn.lovemmd.model.admin.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.NetworkIF;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/v2/metrics")
@Api(tags = "指标统计V2")
@Validated
@RequiredArgsConstructor
public class MetricsControllerV2 {

    private static final Logger log = LoggerFactory.getLogger(MetricsControllerV2.class);

    private final UserService userService;
    private final DownloadLogService downloadLogService;

    @GetMapping(value = "/downloads", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("下载统计（总量/24小时/近7天）")
    public ResponseEntity<String> downloads() {
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("totalDownloads", downloadLogService.getTotalDownloads());
            data.put("last24h", downloadLogService.getDownloadsLast24h());
            data.put("last7d", downloadLogService.getDownloadsLast7d());
            return ResponseEntity.ok(JSON.toJSONString(Result.success(data)));
        } catch (Exception e) {
            log.error("获取下载统计失败", e);
            return ResponseEntity.ok(JSON.toJSONString(Result.error("获取下载统计失败：" + e.getMessage())));
        }
    }

    @GetMapping(value = "/sessions", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("实时会话统计（近似，使用正常用户数代替）")
    public ResponseEntity<String> sessions() {
        try {
            Object stats = userService.getUserStats();
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) stats;
            int normal = 0;
            Object normalObj = map.get("normal");
            if (normalObj instanceof Number) {
                normal = ((Number) normalObj).intValue();
            }
            Map<String, Object> data = new HashMap<>();
            data.put("activeSessions", normal);
            return ResponseEntity.ok(JSON.toJSONString(Result.success(data)));
        } catch (Exception e) {
            log.error("获取会话统计失败", e);
            return ResponseEntity.ok(JSON.toJSONString(Result.error("获取会话统计失败：" + e.getMessage())));
        }
    }

    @GetMapping(value = "/activities", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("最近活动（下载/新增模型）")
    public ResponseEntity<String> activities() {
        try {
            Map<String, Object> data = new HashMap<>();
            List<Map<String, Object>> recentDownloads = downloadLogService.getRecentDownloads(10);
            data.put("downloads", recentDownloads);
            return ResponseEntity.ok(JSON.toJSONString(Result.success(data)));
        } catch (Exception e) {
            log.error("获取最近活动失败", e);
            return ResponseEntity.ok(JSON.toJSONString(Result.error("获取最近活动失败：" + e.getMessage())));
        }
    }

    @GetMapping(value = "/system", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("系统状态（CPU/内存/磁盘/网络，示例占位，可接入OSHI）")
    public ResponseEntity<String> system() {
        try {
            SystemInfo si = new SystemInfo();
            Map<String, Object> data = new HashMap<>();

            // CPU 使用率
            CentralProcessor processor = si.getHardware().getProcessor();
            long[] prevTicks = processor.getSystemCpuLoadTicks();
            try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException ignored) {}
            long[] ticks = processor.getSystemCpuLoadTicks();
            long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
            long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
            long sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
            long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
            long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
            long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
            long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
            long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
            long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;
            int cpuPercent = totalCpu == 0 ? 0 : (int) Math.round(100.0 * (totalCpu - idle) / totalCpu);

            // 内存使用率
            GlobalMemory mem = si.getHardware().getMemory();
            long total = mem.getTotal();
            long available = mem.getAvailable();
            int memPercent = total == 0 ? 0 : (int) Math.round(100.0 * (total - available) / total);

            // 磁盘使用率（粗略，按文件系统总量-可用）
            long diskTotal = si.getOperatingSystem().getFileSystem().getFileStores().stream().mapToLong(fs -> fs.getTotalSpace()).sum();
            long diskUsable = si.getOperatingSystem().getFileSystem().getFileStores().stream().mapToLong(fs -> fs.getUsableSpace()).sum();
            int diskPercent = diskTotal == 0 ? 0 : (int) Math.round(100.0 * (diskTotal - diskUsable) / diskTotal);

            // 网络使用率（占位：取所有网卡每秒字节变化比，归一化为0-100）
            long in1 = 0, out1 = 0;
            for (NetworkIF nif : si.getHardware().getNetworkIFs()) {
                nif.updateAttributes();
                in1 += nif.getBytesRecv();
                out1 += nif.getBytesSent();
            }
            try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException ignored) {}
            long in2 = 0, out2 = 0;
            for (NetworkIF nif : si.getHardware().getNetworkIFs()) {
                nif.updateAttributes();
                in2 += nif.getBytesRecv();
                out2 += nif.getBytesSent();
            }
            long deltaBytes = Math.max(0, (in2 - in1) + (out2 - out1));
            // 简化：假设 100MB/s 近似满载
            int netPercent = (int) Math.max(0, Math.min(100, Math.round(deltaBytes / (100.0 * 1024 * 1024) * 100)));

            data.put("cpu", cpuPercent);
            data.put("memory", memPercent);
            data.put("disk", diskPercent);
            data.put("network", netPercent);
            return ResponseEntity.ok(JSON.toJSONString(Result.success(data)));
        } catch (Exception e) {
            log.error("获取系统状态失败", e);
            return ResponseEntity.ok(JSON.toJSONString(Result.error("获取系统状态失败：" + e.getMessage())));
        }
    }
}
